import 'package:flutter/material.dart';
import 'package:chewie/chewie.dart';
import 'video_player_controller.dart';
import '../utils/error_handler.dart';

/// 自定义UI控制层的构建器
typedef ControlsBuilder = Widget Function(
  BuildContext context,
  NativeAvPlayerController controller,
);

/// 视频播放器Widget
class NativeAvPlayerWidget extends StatefulWidget {
  /// 播放器控制器
  final NativeAvPlayerController controller;

  /// 自定义控制层构建器
  final ControlsBuilder? controlsBuilder;

  /// 是否显示默认控制层
  final bool showDefaultControls;

  /// 播放器背景色
  final Color backgroundColor;

  /// 加载指示器
  final Widget? loadingIndicator;

  /// 错误页面构建器
  final Widget Function(BuildContext context, String error)? errorBuilder;

  const NativeAvPlayerWidget({
    super.key,
    required this.controller,
    this.controlsBuilder,
    this.showDefaultControls = true,
    this.backgroundColor = Colors.black,
    this.loadingIndicator,
    this.errorBuilder,
  });

  @override
  State<NativeAvPlayerWidget> createState() => _NativeAvPlayerWidgetState();
}

class _NativeAvPlayerWidgetState extends State<NativeAvPlayerWidget> {
  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onControllerUpdate);
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onControllerUpdate);
    super.dispose();
  }

  void _onControllerUpdate() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: widget.backgroundColor,
      child: _buildPlayerContent(),
    );
  }

  Widget _buildPlayerContent() {
    final state = widget.controller.state;

    switch (state) {
      case NativeAvPlayerState.idle:
        return _buildIdleWidget();
      case NativeAvPlayerState.loading:
        return _buildLoadingWidget();
      case NativeAvPlayerState.error:
        return _buildErrorWidget();
      case NativeAvPlayerState.ready:
      case NativeAvPlayerState.playing:
      case NativeAvPlayerState.paused:
      case NativeAvPlayerState.buffering:
        return _buildVideoWidget();
      case NativeAvPlayerState.disposed:
        return _buildDisposedWidget();
    }
  }

  Widget _buildIdleWidget() {
    return const Center(
      child: Icon(
        Icons.play_circle_outline,
        size: 64,
        color: Colors.white54,
      ),
    );
  }

  Widget _buildLoadingWidget() {
    return Center(
      child: widget.loadingIndicator ??
          const CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
    );
  }

  Widget _buildErrorWidget() {
    final errorInfo = widget.controller.currentErrorInfo;

    if (widget.errorBuilder != null) {
      // 如果提供了自定义错误构建器，仍然传递原始错误信息
      final error = widget.controller.errorMessage ?? '未知错误';
      return widget.errorBuilder!(context, error);
    }

    // 使用友好的错误信息
    if (errorInfo != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 错误图标
              Text(
                errorInfo.icon,
                style: const TextStyle(fontSize: 64),
              ),
              const SizedBox(height: 16),

              // 错误标题
              Text(
                errorInfo.title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),

              // 错误描述
              Text(
                errorInfo.message,
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                textAlign: TextAlign.center,
              ),

              // 解决建议
              if (errorInfo.suggestions.isNotEmpty) ...[
                const SizedBox(height: 16),
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.black26,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '解决建议：',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 8),
                      ...errorInfo.suggestions.take(3).map(
                            (suggestion) => Padding(
                              padding: const EdgeInsets.only(bottom: 4),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '• ',
                                    style: TextStyle(
                                        color: Colors.white70, fontSize: 12),
                                  ),
                                  Expanded(
                                    child: Text(
                                      suggestion,
                                      style: const TextStyle(
                                        color: Colors.white70,
                                        fontSize: 12,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                    ],
                  ),
                ),
              ],

              const SizedBox(height: 20),

              // 重试按钮
              if (errorInfo.canRetry)
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ElevatedButton.icon(
                      onPressed: () => widget.controller.reload(),
                      icon: const Icon(Icons.refresh),
                      label: const Text('重试'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue,
                        foregroundColor: Colors.white,
                      ),
                    ),
                    const SizedBox(width: 12),
                    // 查看详情按钮（显示原始错误）
                    TextButton(
                      onPressed: () => _showErrorDetails(context, errorInfo),
                      child: const Text(
                        '查看详情',
                        style: TextStyle(color: Colors.white70),
                      ),
                    ),
                  ],
                ),
            ],
          ),
        ),
      );
    }

    // 如果没有分析后的错误信息，回退到原始错误显示
    final error = widget.controller.errorMessage ?? '未知错误';
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          const Text(
            '播放失败',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error,
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 14,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () => widget.controller.reload(),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 显示错误详情对话框
  void _showErrorDetails(BuildContext context, dynamic errorInfo) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('错误详情'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('错误类型：${errorInfo.title}'),
              const SizedBox(height: 8),
              Text('错误描述：${errorInfo.message}'),
              const SizedBox(height: 8),
              const Text('原始错误：'),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  errorInfo.originalError,
                  style: const TextStyle(
                    fontFamily: 'monospace',
                    fontSize: 12,
                  ),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildVideoWidget() {
    if (!widget.controller.isInitialized ||
        widget.controller.chewieController == null) {
      return _buildLoadingWidget();
    }

    return Stack(
      children: [
        // 视频播放器（包含chewie内置控制层）
        Positioned.fill(
          child: AspectRatio(
            aspectRatio: widget.controller.aspectRatio,
            child: Chewie(controller: widget.controller.chewieController!),
          ),
        ),

        // 只有在提供了自定义控制层构建器时才显示
        if (widget.controlsBuilder != null)
          widget.controlsBuilder!(context, widget.controller),
      ],
    );
  }

  Widget _buildDisposedWidget() {
    return const Center(
      child: Text(
        '播放器已释放',
        style: TextStyle(
          color: Colors.white54,
          fontSize: 16,
        ),
      ),
    );
  }
}
